#!/bin/bash

# 编译并运行 PR Sentinel webhook 服务器

set -e

# 颜色输出函数
log_info() { echo -e "\033[32m[INFO]\033[0m $*"; }
log_warn() { echo -e "\033[33m[WARN]\033[0m $*"; }
log_error() { echo -e "\033[31m[ERROR]\033[0m $*" >&2; }
log_fatal() { echo -e "\033[31m[FATAL]\033[0m $*" >&2; exit 1; }

# 1) 加载环境变量文件（如果存在）
if [[ -f .env ]]; then
  log_info "Loading environment variables from .env"
  while IFS= read -r line; do
    # 跳过注释和空行
    [[ "$line" =~ ^#.*$ ]] && continue
    [[ -z "$line" ]] && continue
    # 只导出有效的环境变量行
    if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*=.*$ ]]; then
      export "$line" 2>/dev/null || true
    fi
  done < .env
fi

# 2) 环境变量处理
log_info "Processing environment variables..."

# 统一API密钥变量名（优先使用ANTHROPIC_AUTH_TOKEN）
if [[ -n "${ANTHROPIC_AUTH_TOKEN:-}" ]]; then
  log_info "Using ANTHROPIC_AUTH_TOKEN as API key"
elif [[ -n "${CLAUDE_API_KEY:-}" ]]; then
  log_info "Using CLAUDE_API_KEY as API key"
else
  log_warn "No API key found (CLAUDE_API_KEY or ANTHROPIC_AUTH_TOKEN)"
  log_warn "Some features may not work without API key"
fi

# 3) 配置 Claude CLI 和 MCP 服务
if command -v claude &> /dev/null; then
  log_info "Claude CLI found, configuring..."
  
  # Claude CLI会自动从ANTHROPIC_AUTH_TOKEN环境变量读取API密钥
  if [[ -z "${ANTHROPIC_AUTH_TOKEN:-}" ]]; then
    log_warn "ANTHROPIC_AUTH_TOKEN not set, Claude CLI may not work properly"
  else
    log_info "ANTHROPIC_AUTH_TOKEN is set, Claude CLI will use it automatically"
  fi
  
  # 配置 MCP 服务（强制使用管理器）
  MCP_SERVICE="${MCP_SERVICE:-mcp-gitee}"
  log_info "Configuring MCP service: $MCP_SERVICE"
  
  # 加载MCP管理器（必需）
  if [[ ! -f "mcp/mcp-manager.sh" ]]; then
    log_error "MCP manager not found at mcp/mcp-manager.sh"
    log_warn "MCP service configuration skipped"
  else
    source mcp/mcp-manager.sh
    
    # 加载MCP配置
    if ! load_mcp_config "$MCP_SERVICE"; then
      log_error "Failed to load MCP service configuration: $MCP_SERVICE"
      log_warn "Continuing without MCP service"
    else
      # 配置环境变量
      configure_mcp_env "$MCP_SERVICE"
      
      # 生成Claude CLI配置文件（.claude.json）
      if ! generate_claude_cli_config "$MCP_SERVICE" ".claude.json"; then
        log_error "Failed to generate Claude CLI configuration"
        log_warn "MCP service may not work properly"
      else
        log_info "MCP service configuration completed: $MCP_SERVICE"
      fi
    fi
  fi
else
  log_warn "Claude CLI not found, skipping MCP configuration"
fi

# 清理旧进程
echo "🛑 检查并清理旧进程..."
if pgrep -f "webhook-runner" > /dev/null; then
    echo "   发现运行中的 webhook-runner 进程，正在终止..."
    pkill -f "webhook-runner" || true
    sleep 2
    
    # 强制终止仍在运行的进程
    if pgrep -f "webhook-runner" > /dev/null; then
        echo "   强制终止进程..."
        pkill -9 -f "webhook-runner" || true
        sleep 1
    fi
    echo "   ✅ 旧进程清理完成"
else
    echo "   ✅ 无运行中的进程"
fi

echo "🔧 编译 webhook 服务器..."
cd webhook-runner
go build -o webhook-runner
cd ..

echo "🔑 修复所有脚本执行权限..."
# 修复所有 .sh 文件的执行权限（排除 node_modules 和 .git）
script_count=$(find . -name "*.sh" -type f ! -path "./node_modules/*" ! -path "./.git/*" | wc -l)
find . -name "*.sh" -type f ! -path "./node_modules/*" ! -path "./.git/*" -exec chmod +x {} \;

# 修复 webhook-runner 二进制文件的执行权限
[[ -f "webhook-runner/webhook-runner" ]] && chmod +x webhook-runner/webhook-runner

# 输出统计结果
echo "   ✅ 已修复 $script_count 个脚本文件的执行权限"
[[ -f "webhook-runner/webhook-runner" ]] && echo "   ✅ webhook-runner 执行权限已设置"

echo "🚀 启动 webhook 服务器..."
./webhook-runner/webhook-runner